package com.wsd.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListTypeHandler implements TypeHandler<List<Integer>> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<Integer> integers, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, integers.toString());
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, String s) throws SQLException {
        return parseResult(resultSet.getString(s));
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, int i) throws SQLException {
        return parseResult(resultSet.getString(i));
    }

    @Override
    public List<Integer> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return parseResult(callableStatement.getString(i));
    }

    private List<Integer> parseResult(String str) {
        List<Integer> list = new ArrayList<>();
        if (str == null || str.isEmpty()) return list;

        char[] charArray = str.toCharArray();
        for (char ch : charArray) {
            if (Character.isDigit(ch)) {
                list.add(ch - 48);
            }
        }
        return list;
    }
}
